<?php

/**
 * 库存管理
 * @Author sunge
 * @DateTime  2019-06-19
 */
namespace App\Http\Controllers\Admin;

use App\Exceptions\FormException;
use App\Http\Controllers\Controller;
use App\Models\Goods;
use App\Models\GoodsBrand;
use App\Models\Order;
use App\Models\ReplenishmentLog;
use App\Models\ReplenishmentGoods;
use App\Models\Adminer;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Jobs\ExportData;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\View;
use App\Http\Controllers\LayuiController as Layui;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class StoreController extends Controller
{

    /**
     * 在售库存表
     * @param Request $request
     * @return view
     */
    public function getList(Request $request)
    {
        if (View::exists('Admin/store/index')) {
            return view('Admin/store/index');
        } else {
            return 'View Not Found';
        }
    }

    /**
     * 在售库存表数据
     */
    public function tabelList(Request $request)
    {
        $payload = $request->all([
            'status',
            'keyword'
        ]);
        $status = $request->input('status');
        $goodsList = Goods::with(['goodsBrand','orderGoods','orderGoods.order'])->orderBy('sort','desc')
            ->when($status == Goods::SALE_STATUS_OPEN,function($query)use($status){
                $query->where('status', Goods::SALE_STATUS_OPEN)
                    ->where('stock','>', 0);
            })
            ->when($status == Goods::SALE_STATUS_CLOSE,function($query)use($status){
                $query->where('status', Goods::SALE_STATUS_CLOSE);

            })
            ->when($status == Goods::SALE_STATUS_OUT,function($query)use($status){
                $query->where('stock', 0)->where('status',"!=", Goods::STATUS_CLOSE);
            })
            ->when($keyword = array_get($payload,'keyword'),function($query)use($keyword){
                $query->where(function($query)use($keyword){
                    $query->whereHas('brandInfo', function ($query)use($keyword) {
                        $query->where('name', 'like', "%$keyword%");
                    })
                        ->orWhere('goods_name', 'like', "%$keyword%")
                        ->orWhere('title','like', "%$keyword%")
                        ->orWhere('sku','like', "%$keyword%");
                });

            }) ->paginate($request->get('limit',10));

        $total = $goodsList->total();

        $goodsList = $goodsList->map(function($item){
            $filter7 = collect($item->orderGoods)->filter(function($value, $key) {
                if ($value->order->status == Order::STATUS_SUCCESS  and $value['created_at'] < strtotime("-7 day")) {
                    return true;
                }
            });
            $filter = collect($item->orderGoods)->filter(function($value, $key) {
                if ($value->order->status == Order::STATUS_SUCCESS) {
                    return true;
                }
            });
            return [
                'id'         => $item->id,
                "goods_name" => $item->goods_name,
                "title" => $item->title,
                "sku" => $item->sku,
                "price" => round($item->price,2),
                "stock" => $item->stock,
                "photo" => $item->photo,
                "brand" => $item->brand,
                "status" => $item->status,
                "order_goods" => $item->orderGoods,
                "goods_brand" => $item->goodsBrand,
                "amount_sum"=>collect($filter)->sum('amount'),
                "amount_sum7"=>collect($filter7)->sum('amount')
                ];
        });

        return Layui::tableJson($goodsList,0,$total);
    }

    /**
     * 补货页
     */
    public function padList()
    {
        return view('Admin/store/padList');
    }

    /**
     * 补货数据
     */
    public function padListTabel(Request $request)

    {
        $payload = $request->all(['keyword','time','status']);
        $status = $request->input('status');
        $goodsList = Goods::with(['orderGoods','goodsBrand'])->orderBy('sort','desc')
            ->when($keyword = array_get($payload,'keyword'),function($query)use($keyword){
                $query->where(function($query)use($keyword){
                    $query->whereHas('brandInfo', function ($query)use($keyword) {
                        $query->where('name', 'like', "%$keyword%");
                    })
                        ->orWhere('goods_name', 'like', "%$keyword%")
                        ->orWhere('title','like', "%$keyword%")
                        ->orWhere('sku','like', "%$keyword%");
                });
            })
            ->when($status == Goods::SALE_STATUS_OPEN,function($query)use($status){
                $query->where('status', Goods::SALE_STATUS_OPEN)
                    ->where('stock','>', 0);
            })
            ->when($status == Goods::SALE_STATUS_CLOSE,function($query)use($status){
                $query->where('status', Goods::SALE_STATUS_CLOSE);

            })
            ->when($status == Goods::SALE_STATUS_OUT,function($query)use($status){
                $query->where('stock', 0);
            })
//            ->get(10);
            ->paginate($request->get('limit',10));

        return Layui::tableJson($goodsList,0,$goodsList->total());
    }

    /**
     * ajax 验证补货单号唯一性
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function orderno(Request $request)
    {
        $order_no = $request->input("order_no");
        if(ReplenishmentLog::where("order_no",$order_no)->first()){
            return $this->getResponse('补货单号不唯一,请重新填写', $data = [], $code = 0);
        }else{
            return $this->getResponse('1');
        }
    }

    /**
     * 补货数据保存
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws FormException
     */
    public function savePad(Request $request)
    {
        if ($request->isMethod('post')) {
            $load = $request->all([
                'amount',
                'order_no',
                'skunum',
                'remark',
                'pad'
            ]);
            Validator::make($load, [
                'amount'     =>'required',
                'order_no'   =>'required|unique:replenishment_log',
                'skunum'     =>'required'

            ], [
                'amount.required'     =>'请输入补货商品数量',
                'order_no.unique' =>'补货单号必须唯一',
                'order_no.required'          =>'请输入补货商品单号',
                'skunum.required'          =>'请输入补货品类数',
            ])->validate();

            \DB::beginTransaction();
            try{
                $pad = explode(",",rtrim($load['pad'],",")) ;
                unset($load['pad']);
                $load['creater'] = Auth::guard('admin')->user()->id;
                $load['created_at'] = date("Y-m-d H:s:i");
                $log_id = ReplenishmentLog::create($load)->id;
                foreach($pad as $key =>$value){
                    $va = explode("@",$value);
                    $replenishmentGoods = new ReplenishmentGoods();
                    $replenishmentGoods->replenishment_log_id =$log_id;
                    $replenishmentGoods->goods_id = $va[0];
                    $replenishmentGoods->goods_num = $va[1];
                    $replenishmentGoods->created_at = date("Y-m-d H:i:s");
                    $replenishmentGoods->save();
                    $Goods = Goods::find($va[0]);
                    $Goods->update([
                        'stock' => (int)$Goods->stock + $va[1],
                        'updated_at' => date("Y-m-d H:i:s"),
                    ]);
                }

            }catch (\Exception $exception){
                \DB::rollBack();
                throw new FormException(\App::environment('local') ? $exception->getMessage() : '保存失败' );
            }
            \DB::commit();
            return $this->getResponse('保存成功');
        }
    }

    /**
     * 补货记录页
     */
    public function padRecord()
    {

        return view('Admin/store/padRecord');
    }

    /**
     * 补货记录数据
     */
    public function padRecordTable(Request $request)
    {
        $payload = $request->all(['time','creater']);
        $list = ReplenishmentLog::with(['adminer'])->orderBy('id','desc')
            ->when($creater = array_get($payload,'creater'),function($query)use($creater){
                $query->whereHas('adminer',function($query)use($creater){
                    $query->where('username','like',"%$creater%");
                });

            })
            ->when($time = array_get($payload,'time'),function($query)use($time){
                $time = explode(' - ',$time);
                $time[1] = Carbon::parse($time[1])->addDay()->toDateString();
                $query->whereBetween('created_at',$time);
            })
            ->paginate($request->get('limit',10));
        return Layui::tableJson($list,0,$list->total());
    }

    /**
     * 补货记录详情页
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function padRecordDetail($id)
    {
        return view('Admin/store/padRecordDetail', compact('id'));

    }
    /**
     * 补货详情页数据--补货记录单条
     * @param Request $request
     * @param $id
     * @return array
     */
    public function padRecordTableById(Request $request,$id)
    {
        $list = ReplenishmentLog::with(['adminer'])->where('id',$id)->get()->toArray();
        return Layui::tableJson($list,0,count($list));
    }

    /**
     * 补货详情页数据--补货商品
     * @param $id
     * @return array
     */
    public function padRecordDetailTable($id)
    {
        $list = ReplenishmentGoods::with(['goods'])->where("replenishment_log_id",$id)->get();
        if(!empty($list)){
            $list = $list->map(function($item){
                return [
                    'id'         => $item->id,
                    "goods_id" => $item->goods_id,
                    "goods_num" => $item->goods_num,
                    "created_at" => $item->sku,
                    "replenishment_log_id" => $item->replenishment_log_id,
                    'goods'=>isset($item->Goods)? :"",
                    'goodsbrand'=>isset($item->Goods)? GoodsBrand::find($item->Goods->brand)->name:""

                ];
            });
        }

        return Layui::tableJson($list,0,count($list));
    }

    /**
     * 补货记录导出excel
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function export(Request $request)
    {
        $payload = $request->all();
        $filename = $request->input('filename','demo.csv');
        $filename = rtrim($filename,'.csv').'.csv';

        if(Storage::disk('exports')->exists($filename))
            return $this->getResponse('文件已存在，请重新输入',[],302,url('admin/user/index'));
        //判断前台是否有选择
        if(empty($payload['ids'])){
            /* 获取查询条件 */
            $payload = $request->all(['time','creater']);
            $preData = ReplenishmentLog::with(['adminer'=>function($query)use($payload){
                $query->when($creater = array_get($payload,'creater'),function($query)use($creater){
                    $query->where('username','like',"%$creater%");
                });
            }])->orderBy('id','desc')
                ->when($time = array_get($payload,'time'),function($query)use($time){
                    $time = explode(' - ',$time);
                    $time[1] = Carbon::parse($time[1])->addDay()->toDateString();
                    $query->whereBetween('created_at',$time);
                })
                ->get();
        }else{
            //有选择
            $ids = explode(',',$payload['ids']);
            $preData = ReplenishmentLog::with(['adminer'])
                ->whereIn( 'id', $ids)
                ->orderBy('id','desc')
                ->get();
        };

        if( count($preData) == 0 ){
            return $this->getResponse('导出不能为空，请重新尝试',[],302,url('admin/user/index'));
        }
        $data = $preData->map(function($item){
            $item->username = $item->Adminer->username;
            return $item;
        });

        /* 定义文件头 */
        $header = [
            'created_at'  => '补货时间',
            'order_no'     => '补货单号',
            'phone'      => '操作人',
            'skunum'      => '补货品类数量',
            'amount' => '补货数量',
            'remark' => '补货事由'
        ];

        /* 插入队列 */
        /* 闭包序列化处理 */
        //$serializer = new Serializer();
        dispatch(new ExportData($header,'','',$filename,$data->toArray()));
        return $this->getResponse('已加入导出队列',[],200,url('admin/partner'));
    }

    /**
     * 补货记录详情导出excel
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function exportdetail(Request $request){
        $payload = $request->all();
        $filename = $request->input('filename','demo.csv');
        $filename = rtrim($filename,'.csv').'.csv';

        if(Storage::disk('exports')->exists($filename))
            return $this->getResponse('文件已存在，请重新输入',[],302,url('admin/user/index'));

        $list = ReplenishmentGoods::with(['goods'])->where("replenishment_log_id",$payload['id'])->get();
        $list = $list->map(function($item){
                $item->brand=GoodsBrand::find($item->Goods->brand)->name;
                $item->title=$item->Goods->title;
                $item->photo=$item->Goods->photo;
                $item->sku=$item->Goods->sku;
            return $item;

        });
        if( count($list) == 0 ){
            return $this->getResponse('导出不能为空，请重新尝试',[],302,url('admin/user/index'));
        }

        /* 定义文件头 */
        $header = [
//            'photo'  => '商品图片',
            'title'     => '商品名称',
            'sku'      => '商品编码',
            'brand'      => '商品品牌',
            'goods_num' => '补货数量',
        ];

        /* 插入队列 */
        /* 闭包序列化处理 */
        //$serializer = new Serializer();
        dispatch(new ExportData($header,'','',$filename,$list->toArray()));
        return $this->getResponse('已加入导出队列',[],200,url('admin/partner'));
    }
}
